package tools;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.text.DecimalFormat;
import java.util.ArrayList;

public class LogProcessor {
	public static void main(String[] argv){
		BufferedReader in;
		Double minAvgFit = Double.MAX_VALUE; 
		Double minFit = Double.MAX_VALUE; 
		 try {
			double minimum = 323537.0;
			ArrayList<String[]> matrix = new ArrayList<String[]>();
			in = new BufferedReader(new FileReader("templogs.txt"));
			Integer density = 0;
			String gene = "";
			ArrayList<Double> values = new ArrayList<Double>();
			while(in.ready() == true){
				String line = in.readLine();
				String[] typeSplit = line.split(":");
				if(typeSplit.length == 0){
					continue;
				}
				if(typeSplit[0].equals("Agent_spawn_interval")){
					density = 1000/Integer.parseInt(line.split(" ")[1]);
				}
				if(typeSplit[0].equals("Fitness/Agent")){
					if(Double.parseDouble(line.split(" ")[1]) < minFit){
						minAvgFit = Double.parseDouble(line.split(" ")[1]);
					}
				}
				if(typeSplit[0].equals("Gene")){
					if(gene.length() == 0){
						gene = line;
					} else {
						gene += " "+line;
					}
				}
				if(typeSplit[0].equals("Fitnesses")){
					String[] x = line.split(" ");
					for(int i = 1; i < x.length ; i++){
						Double val = Double.parseDouble(x[i]);
						if(val < minFit){
							minFit = val;
						}
						Double valProc = minimum/Double.parseDouble(x[i])*100;
						x[i] = valProc.toString();
					}
					x[0] = density.toString();
					matrix.add(x);
				}
				if(typeSplit[0].equals("Stopped_at")){
					if(density == 1000){
						printMatrix(matrix,gene);
						matrix.clear();
						gene = "";
					}
				}
			}
			System.out.println(minFit);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static void printMatrix(ArrayList<String[]> matrix,String gene) {
		System.out.println(gene);
		for(int i = 0; i < matrix.get(0).length;i++){
			for(int j = 0; j < matrix.size(); j++){
			    DecimalFormat df = new DecimalFormat("#.#####");
			    double y = Double.parseDouble(matrix.get(j)[i]);
			    System.out.print(df.format(y)+"\t");
			}
			System.out.println();
		}
	}
}